<?php 
function connect()
{
	$link = @mysql_connect('localhost','root','')
	or die("<p>无法连接数据库！</p>");
	mysql_set_charset('utf8');
   mysql_select_db('users');

/*	or die("<p>无法查询数据库！</p>");
	return $link;*/
}
function fetch_array($sql,$result_type=MYSQL_ASSOC){
    $result=mysql_query($sql);
    if ($result && mysql_num_rows($result)>0){
        while ($row=mysql_fetch_array($result,$result_type)){
            $rows[]=$row;
        }
        return $rows;
    }else {
        return false;
    }
}
function fetch_one($sql,$result_type=MYSQL_ASSOC){
    $result=mysql_query($sql);
    if ($result && mysql_num_rows($result)>0){
        return mysql_fetch_array($result,$result_type);
    }else {
        return false;
    }
}


//插入操作
function add($tbl,$data){
  $keys = implode(',',array_keys($data));
  $values = implode("','", array_values($data));
  $sql="insert into {$tbl} ({$keys}) VALUES ('{$values}')";
  $result = mysql_query($sql);
  if($result===FALSE){
    return false;
  }
  else{
    return mysql_insert_id();
  }
}

//更新操作
function update($tbl,$data,$where=null){
  $sets='';
    foreach ($data as $key=>$val){
        $sets .=$key . "='" . $val . "',";
    }
    $sets=rtrim($sets,','); //去掉SQL里的最后一个逗号
    $where=$where==null?'':' WHERE '.$where;
    $sql="UPDATE {$tbl} SET {$sets} {$where}";  
    $res=mysql_query($sql);
    if ($res){
        return mysql_affected_rows();
    }else {
        return false;
    }
}
//删除操作
function delete($tbl,$where=null){
    $where=$where==null?'':' WHERE '.$where;
    $sql="DELETE FROM {$tbl}{$where}";
    $res=mysql_query($sql);
    if ($res){
        return mysql_affected_rows();
    }else {
        return false;
    }
}



?>
